package org.micode.demo.biz;

import org.micode.common.config.ApplicationConfig;
import org.micode.common.consts.HttpHeadConsts;
import org.micode.common.domain.base.BaseUserCache;
import org.micode.common.domain.base.IUserCache;
import org.micode.common.helper.I18nMsgHelper;
import org.micode.common.utils.BeanExtUtils;
import org.micode.common.utils.JsonUtils;
import org.micode.common.utils.StringExtUtils;
import org.micode.libs.servlet.utils.HttpContextUtils;
import org.micode.demo.db.syslog.BaseDaoSysLogSaver;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public abstract class ServletSysLogSaver extends BaseDaoSysLogSaver {

    @Override
    protected String readAppModuleId() {
        return ApplicationConfig.MODULE_ID;
    }

    @Override
    public String getLoginApp(Object[] args) {
        String app = HttpContextUtils.getClientApp();
        if (StringExtUtils.isAnyEmpty(app)) {
            app = ApplicationConfig.SERVICE_NAME;
        }
        return app;
    }

    @Override
    public String getRemoteIp(Object[] args) {
        return HttpContextUtils.getIp();
    }

    @Override
    public String getParams(Object[] args) {
        for (Object arg : args) {
            if (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse)) {
                try {
                    return JsonUtils.toJson(arg);
                } catch (Exception e) {
                    log.error(I18nMsgHelper.get("fail.ServletSysLogSaver-getParams.call") + ", args:{}", args, e);
                    return "[\"" + I18nMsgHelper.get("fail.ServletSysLogSaver-getParams.call") + "\"]";
                }
            }
        }
        return "";
    }

    @Override
    public Long getCurrentUserId(Object[] args) {
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        if (null == request) {
            return null;
        }
        Long ret = currentUserIdFromCache(request);
        if (null == ret) {
            ret = currentUserIdFromHeader(request);
        }
        return ret;
    }


    @Override
    public Integer getUserType(Object[] args) {
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        if (null == request) {
            return null;
        }
        return currentUserTypeFromHeader(request);
    }

    protected Integer currentUserTypeFromHeader(HttpServletRequest request) {
        IUserCache user = (BaseUserCache)request.getAttribute(HttpHeadConsts.REQUEST_USER_KEY);
        if (null == user) {
            return null;
        } else {
            return user.getUserType();
        }
    };

    @Override
    public String getCurrentUserToken(Object[] args) {
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        if (null != request) {
            return currentUserTokenFromHeader(request);
        } else {
            for (Object obj : args) {
                if (BeanExtUtils.findFieldByName(obj, "token")) {
                    return (String)BeanExtUtils.getFieldValueByName(obj, "token");
                }
            }
        }
        return null;
    }

    private String currentUserTokenFromHeader(HttpServletRequest request) {
        return (String)request.getAttribute(HttpHeadConsts.REQUEST_QUERY_TOKEN_KEY);
    }

    private Long currentUserIdFromHeader(HttpServletRequest request) {
        IUserCache user = (BaseUserCache)request.getAttribute(HttpHeadConsts.REQUEST_USER_KEY);
        if (null == user) {
            log.warn(I18nMsgHelper.get("fail.HttpServletRequest-getAttribute.not-user"));
            return null;
        } else {
            return user.getUserId();
        }
    }

    private Long currentUserIdFromCache(HttpServletRequest request) {
        String ret = request.getHeader(HttpHeadConsts.REQUEST_HEADER_USERID_KEY);
        if (!StringUtils.isEmpty(ret)) {
            try {
                return Long.parseLong(ret.trim());
            } catch(Exception e) {
                log.warn(I18nMsgHelper.get("fail.HttpServletRequest-getHeader.not-userId") + "({})", ret.trim());
            }
        }
        return null;
    }

}
